<template>
  <basic-container>
    <avue-crud
      ref="crud"
      :option="option"
      :data="data"
      :page.sync="page"
      @selection-change="handleSelectionChange"
      :table-loading="listLoading"
      @search-change="searchChange"
      @refresh-change="refreshChange"
      @current-change="currentChange"
      @size-change="sizeChange"
    >
      <!-- 供应订单编号 -->
      <template slot="supplySn" slot-scope="scope">
        <span
          @click="supplyOrderSerial(supplySn)"
          v-for="(supplySn, index) in scope.row.supplySn"
          :key="index"
          style="display: flex; color: #409EFF"
        >
          <span>{{supplySn}}</span>
        </span>
      </template>
      <!-- 弹框 -->
      <!-- <template>
        <el-button type="text" @click="open">点击打开 Message Box</el-button>
      </template>-->
      <!-- 批量下单按钮 -->
      <template slot="menuLeft" slot-scope="scope">
        <el-button type="primary" size="small" @click="multiplChoiceBatch()">一键向供应商下单</el-button>
      </template>
      <template slot="menu" slot-scope="scope">
        <el-button type="text" size="small" @click="details(scope.row)">详情</el-button>
        <el-button
          v-show="scope.row.status!=3"
          type="text"
          size="small"
          @click="multiplChoice(scope.row)"
        >向供应商下单</el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>
<script>
import { tableOption } from "../../const/crud/supply/purchase_order";
import { purchaseOrder } from "../../api/supply/purchase_order";
import {
  purchaseaddOrder,
  purchaseRelation
} from "../../api/supply/purchase_add";
export default {
  name: "supply",
  data() {
    return {
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条,
        isAsc: false // 是否倒序
      },
      option: tableOption,
      purchaseOrder: purchaseOrder,
      // 选中的数据
      choseData: [],
      purchaseOption: [],
      data: [],
      listLoading: true,
      payStatus: ""
    };
  },
  computed: {
    searchForm() {
      return this.$refs.crud.searchForm;
    }
  },
  mounted() {
    let queryParams = this.$route.query.res;

    if (queryParams) {
      this.searchForm.orderSn = queryParams.orderSn;
    }
    this.getPurchase(this.page, this.searchForm.orderSn);
    this.getHeight();
  },
  methods: {
    getHeight() {
      let tableHeight = Math.max(window.innerHeight - 430, 300);
      this.option.maxHeight = tableHeight + "px";
    },
    // 单个下单
    async multiplChoice(data) {
      let params = {
        buyOrderSn: data.buyOrderSn
      };
      await purchaseaddOrder(params).then(res => {
        console.log(res);
        if (data.payStatus == 0) {
          this.$confirm("订单未支付, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              let reData = res.data.data;
              console.log(reData);

              if (reData.status == true) {
                this.$message.success(reData.buyOrderSn);
                this.$set(data, "supplyMsg", reData.msg);
              } else {
                // 错误提示
                this.$message.error(reData.msg);
                this.$set(data, "supplyMsg", reData.msg);
              }
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消向供应商下单"
              });
            });
        }
      });
    },
    //批量下单
    async multiplChoiceBatch() {
      let buyIds = [];
      let choseData = this.choseData;
      let localData = this.data;
      this.choseData.forEach(function(item, index) {
        buyIds.push(item.buyOrderSn);
      });
      let that = this;
      await purchaseaddOrder({ buyOrderSnList: buyIds }, true).then(res => {
        console.log(res);
        if (that.payStatus == 0) {
          that
            .$confirm("订单未支付, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
            .then(() => {
              let reData = res.data.data;
              let successNum = 0;
              let failNum = 0;
              if (res.data.code === 0) {
                reData.list.forEach(function(val, key) {
                  that.data.forEach(function(item, index) {
                    if (item.buyOrderSn === val.buyOrderSn) {
                      if (val.status) {
                        successNum++;
                        that.$set(item, "supplyMsg", val.msg);
                      } else {
                        failNum++;
                        that.$set(item, "supplyMsg", val.msg);
                      }
                      console.log(item.supplyMsg);
                    }
                  });
                });
                // 弹窗
                this.$alert(
                  "成功数:" + successNum + ";失败数：" + failNum,
                  "供应下单结果",
                  {
                    confirmButtonText: "确定"
                  }
                );
              }
            }).catch(() => {
              this.$message({
                type: "info",
                message: "已取消向供应商下单"
              });
            });
        }
      });
    },

    // 请求数据
    getPurchase(page, params) {
      this.listLoading = true;
      purchaseOrder(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params
        )
      ).then(res => {
        let list = res.data.data.records;
        let that = this;
        list.forEach(element => {
          element.supplyMsg = "";
          (function(buyOrderSn) {
            purchaseRelation(buyOrderSn).then(res => {
              let info = res.data.data;
              that.payStatus = info.payStatus;
              if (info.status) {
                element.supplyMsg = "已下单";
                element.supplySn = info.supplySns.split(",");
                element.payStatus = info.payStatus;
              } else {
                element.supplyMsg = "未下单";
                element.supplySn = info.supplySns.split(",");
                element.payStatus = info.payStatus;
              }
            });
          })(element.buyOrderSn);
        });
        this.data = list;
        this.page.total = res.data.data.total;
        this.listLoading = false;
      });
    },

    setInfo(buyOrderSn) {
      let that = this;

      purchaseRelation(buyOrderSn).then(res => {
        let info = res.data.data;

        for (let i = 0; i < this.data.length; i++) {
          // debugger;
          if (that.data[i].buyOrderSn === buyOrderSn) {
            if (info.status) {
              that.data[i].supplyMsg = "是";
            } else {
              that.data[i].supplyMsg = "否";
            }
            break;
          }
        }
      });
    },

    // 这儿是选中数据
    handleSelectionChange(val) {
      this.choseData = val;
      this.multipleSelection = val;
    },
    // 详情
    details(row) {
      let query = {
        res: {
          buyOrderSn: row.buyOrderSn
          // supplySn: row.supplySn
        }
      };
      console.log(query);
      this.$router.push({
        path: "/supply/purchasedeatilssupplygoods",
        query: query
      });
    },
    /**
     * 搜索回调
     */
    searchChange(form, done) {
      console.log(form);
      this.getPurchase(this.page, form);
      done();
    },
    /**
     * 刷新回调
     */
    refreshChange() {
      this.getPurchase(this.page, this.filterForm(this.searchForm));
    },
    currentChange(val) {
      console.log(val);
      this.page.currentPage = val;
      this.getPurchase(this.page);
      // this.$message.success("页码" + val);
    },
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
      this.getPurchase(this.page);
      // this.$message.success("行数" + val);
    },
    // 点击供应订单编号
    supplyOrderSerial(supplySn) {
      let query = {
        res: {
          supplySn: supplySn
        }
      };
      this.$router.push({ path: "/supply/supplyOrderDetail", query: query });
    }
  }
};
</script>